import { login, qrCodeLogin, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { isExternal } from "@/utils/validate";

const LOGIN_TIMESTAMP_KEY = "william-login-at";

function setLoginTimestamp() {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(LOGIN_TIMESTAMP_KEY, Date.now().toString());
  } catch (error) {
    // ignore storage limitations
  }
}

function clearLoginTimestamp() {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.removeItem(LOGIN_TIMESTAMP_KEY);
  } catch (error) {
    // ignore storage limitations
  }
}

function resolveMediaUrl(path) {
  const raw = path === undefined || path === null ? "" : String(path).trim();
  if (!raw) {
    return "";
  }
  if (isExternal(raw)) {
    return raw;
  }
  const join = (prefix, sub) => {
    if (!prefix) {
      return sub.startsWith("/") ? sub : `/${sub}`;
    }
    const safePrefix = prefix.replace(/\/$/, "");
    const safeSub = sub.startsWith("/") ? sub : `/${sub}`;
    return `${safePrefix}${safeSub}`;
  };
  const apiBase = process.env.VUE_APP_BASE_API || "";
  const fileBase = process.env.VUE_APP_FILE_BASE_URL || "";
  let base = fileBase || apiBase;
  if (!base && typeof window !== "undefined") {
    base = window.location.origin || "";
  }
  return join(base, raw);
}

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            setLoginTimestamp();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 二维码登录
    qrCodeLogin({ commit }, userInfo) {
      // 公众号体验用户
      const username = "18758268181";
      const password = "123456";
      return new Promise((resolve, reject) => {
        qrCodeLogin(username, password)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            setLoginTimestamp();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;
            const avatarUrl = resolveMediaUrl(user && user.avatar);
            const avatar = avatarUrl
              ? avatarUrl
              : require("@/assets/images/profile.jpg");
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", user.userName);
            commit("SET_AVATAR", avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            clearLoginTimestamp();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        clearLoginTimestamp();
        resolve();
      });
    },
  },
};

export default user;
